import React, { useState, useEffect, useRef } from "react";
import GeekIcon from "../../components/Icon";
import { FillinOutline } from "antd-mobile-icons";
import { Popup, Skeleton, Toast } from "antd-mobile";
import styles from "./index.module.scss";
import { useInitialState } from "@/utils/use-initial-state";
import { useParams, useLocation, useHistory } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import {
  collectArticle,
  followAuthor,
  getArticleById,
  getArticleComment,
  getMoreArticleComments,
  likeArticle,
} from "@/store/actions/article";
import dayjs from "dayjs";
import throttle from "lodash/throttle";
import CommentFooter from "../CommentFooter";
import CommentInput from "../CommentInput";
import CommentItem from "../CommentItem";
import Icon from "../../components/Icon";
import { times } from "lodash";
type obj = {
  total_count: any;
  results: any;
};
const Article = ({ articleId }: any) => {
  // 从redux获取评论数据
  const comments = useSelector((state: any) => state);
  console.log(comments, "commentscommentscomments");

  // 评论抽屉
  const [commentVisible, setCommentVisible] = useState(false);
  const onCommentShow = () => setCommentVisible(true);
  const onCommentHide = () => setCommentVisible(false);

  const wrapperRef = useRef<HTMLDivElement>(null);
  const authorRef = useRef<HTMLDivElement>(null);
  const [showNavAuthor, setShowNavAuthor] = useState(false);
  const history = useHistory();
  const [article, setArticle] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const dispatch: any = useDispatch();
  const location = useLocation();
  const pathname = location.pathname;
  const pathArray = pathname.split("/");
  const artId = pathArray[pathArray.length - 1];
  let [list, setList]: obj | any = useState({});
  // 创建枚举，来表示评论类型
  enum CommentType {
    Article = "a",
    Comment = "c",
  }
  let getList = async () => {
    let res = await getArticleComment(CommentType.Article, artId);
    setList(res.data.data);
  };
  useEffect(() => {
    getList();
    const fetchData = async () => {
      // 获取评论数据

      const articleData = await getArticleById(artId ?? "");
      setArticle(articleData);
      setLoading(false);
    };
    fetchData();
  }, []);

  if (!article) {
    return <div className={styles.root}>文章资源加载中，请稍后!!!</div>;
  }

  const {
    art_id,
    aut_id,
    attitude,
    is_collected,
    content,
    is_followed,
    aut_name,
    aut_photo,
    comm_count,
    like_count,
    pubdate,
    read_count,
    title,
  } = article;
  // 点击关注
  const onFollow = () => {
    try {
      dispatch(followAuthor(aut_id, is_followed));
      setArticle((prevArticle: any) => ({
        ...prevArticle,
        is_followed: !is_followed,
      }));
      Toast.show(is_followed ? "取消关注" : "已关注");
    } catch {}
  };
  // 获取评论信息
  // const { comment } = useInitialState(
  //   () => getArticleById(artId),
  //   "article",
  //   // () => setLoading(false)
  // );
  // 文章评论;
  // const { end_id, last_id } = comment;
  // 是否有更多评论;
  // const hasMoreComment = end_id !== last_id;
  // const loadMoreComments = async () => {
  //   await dispatch(
  //     getMoreArticleComments(CommentType.Article, artId, comment.last_id)
  //   );
  // };
  // 渲染评论抽屉
  const renderComments = () => {
    console.log(111); // 你可以根据需要决定是否保留这个 console.log
    return (
      <>
        {list?.total_count === 0 ? (
          <span>还没有人评论哦</span>
        ) : (
          <div className="comment-list">
            {/* <Header
              title={`全部评论${data?.total_count}`}
              className={styles.commentssss}
            ></Header> */}
            {list.results?.map((item: any) => (
              <div
                key={item.com_id}
                style={{ display: "flex", height: "90px" }}
              >
                <div style={{ width: "50px", height: "50px" }}>
                  <img
                    src={item.aut_photo}
                    alt=""
                    style={{
                      width: "30px",
                      height: "30px",
                      borderRadius: "15px",
                      verticalAlign: "center",
                      marginLeft: "6px",
                      marginTop: "6px",
                    }}
                  />
                </div>
                <div style={{ width: "220px" }}>
                  <p style={{ marginTop: "8px" }}>{item.aut_name}</p>
                  <p style={{ marginTop: "8px" }}>{item.content}</p>
                  <p style={{ marginTop: "8px" }}>
                    <span
                      style={{
                        padding: "5px",
                        borderRadius: "10px",
                        background: "#DDD",
                      }}
                      // onClick={() => onCommentReplyShow(item)}
                    >
                      0回复 &gt;
                    </span>
                    &nbsp;&nbsp;&nbsp;
                    <span>{times(item.pubdate)}</span>
                  </p>
                </div>
                <div style={{ width: "50px", lineHeight: "50px" }}>
                  {item.like_count}
                  &nbsp;&nbsp;&nbsp;
                  <Icon
                    type={item.is_liking ? "iconbtn_like_sel" : "iconbtn_like2"}
                    // onClick={() => onThumbsUp(item.com_id, item.is_liking)}
                  />
                </div>
              </div>
            ))}
          </div>
        )}
      </>
    );
  };

  //   <div>
  //     {/* {comments.data.map((comment: any) => {
  //       <CommentItem key={comment.id} {...comment} />;
  //     })} */}

  //   </div>
  // if (comm_count === 0) {
  //   return <NoneComment />;
  // } else {
  //   return (
  //     <div className="comment-list">
  //       {results.map((item: any) => {
  //         return <CommentItem key={item.com_id} {...item} />;
  //       })}
  //     </div>
  //   );
  // }

  // const onAddComment = async (content: string) => {
  //   await dispatch(addArticleComment(art_id.content));
  //   onCommentHide();
  // };
  // 评论信息
  const renderCommentPopup = () => {
    function onAddComment(content: string): void {
      throw new Error("Function not implemented.");
    }

    return (
      <Popup
        className="comment-popup"
        position="bottom"
        visible={commentVisible}
        onMaskClick={onCommentHide}
      >
        {renderComments()}
        <div className="comment-popup-wrapper">
          <CommentInput onAddComment={onAddComment} />
        </div>
      </Popup>
    );
  };
  // 收藏和取消收藏
  const onCollected = async () => {
    try {
      await dispatch(collectArticle(art_id, is_collected));
      setArticle((prevArticle: any) => ({
        ...prevArticle,
        is_collected: !is_collected,
      }));
      Toast.show(is_collected ? "取消收藏" : "已收藏");
    } catch {}
  };
  // 点赞 或 取消点赞 -- 文章
  const onLike = async () => {
    try {
      await dispatch(likeArticle(art_id, attitude));
      setArticle((prevArticle: any) => ({
        ...prevArticle,
        attitude: !attitude,
      }));
      Toast.show(attitude ? "取消点赞" : "已点赞");
    } catch {}
  };
  return (
    <div style={{ height: "100vh", overflow: "hidden" }}>
      <div className={styles.header}>
        <div className={styles.left}>
          <h3 onClick={() => history.push("/home/index")}>&lt;</h3>
          <div className={styles.center}>
            <img src={aut_photo} alt="" />
            <span>{aut_name}</span>
            <button onClick={onFollow}>
              {is_followed ? "已关注" : "关注"}
            </button>
          </div>
        </div>
        <GeekIcon type={"icongengduo"} className={styles.more} />
      </div>
      <div className={styles.article}>
        <h2 className={styles.title}>{title}</h2>
        <div className={styles.meta}>
          <span>{dayjs(pubdate).locale("zh-cn").format("LL")}</span>
          <span>{read_count} 阅读</span>
          <span>{comm_count} 评论</span>
        </div>
        <div className={styles.author}>
          <div className={styles.avatar}>
            <img src={aut_photo} alt="" />
            <span>{aut_name}</span>
          </div>
          <div className={styles.follow}>
            <button onClick={onFollow}>
              {is_followed ? "已关注" : "关注"}
            </button>
          </div>
        </div>
        <div className={styles.content}>
          <div dangerouslySetInnerHTML={{ __html: content }}></div>
          <div className={styles.footnote}>
            文章发布于：
            {dayjs(pubdate).locale("zh-cn").format("LL")}
          </div>
        </div>
        <div className={styles.bar}>
          <div className={styles.sofa}>
            <FillinOutline className={styles.icon} />
            <span>去评论</span>
          </div>
          <div className={styles.icons}>
            <div className={styles.item} onClick={renderComments}>
              <GeekIcon type={"iconbtn_comment"} />
              <span>评论</span>
            </div>
            <div className={styles.item} onClick={onLike}>
              <GeekIcon
                type={attitude ? "iconbtn_like_sel" : "iconbtn_like2"}
              />
              <span>点赞{attitude}</span>
            </div>
            <div className={styles.item} onClick={onCollected}>
              <GeekIcon
                type={is_collected ? "iconbtn_collect_sel" : "iconbtn_collect"}
              />
              <span>收藏{comm_count}</span>
            </div>
            <div className={styles.item}>
              <GeekIcon type={"iconbtn_share"} />
              <span>分享</span>
            </div>
          </div>
        </div>
        {renderComments()}
      </div>
      <div>
        <CommentFooter
          onCommentPopup={onCommentShow}
          type={""}
          onCollected={function (): void {
            throw new Error("Function not implemented.");
          }}
        />
      </div>
    </div>
  );
};

export default Article;
